package a66weding.com.jiehuntong.pager;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.animation.FastOutSlowInInterpolator;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.Interpolator;
import android.view.animation.LayoutAnimationController;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import org.greenrobot.eventbus.Subscribe;
import org.xutils.common.util.DensityUtil;
import org.xutils.x;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import a66weding.com.jiehuntong.MainActivity;
import a66weding.com.jiehuntong.R;
import a66weding.com.jiehuntong.activity.Diy_HeadActivity;
import a66weding.com.jiehuntong.activity.FindHelp;
import a66weding.com.jiehuntong.activity.JobDetail;
import a66weding.com.jiehuntong.activity.JobDetailActivity;
import a66weding.com.jiehuntong.activity.LoginActivity;
import a66weding.com.jiehuntong.activity.MyTaskActivity;
import a66weding.com.jiehuntong.application.DataWareHourse;
import a66weding.com.jiehuntong.application.GlobalApplication;
import a66weding.com.jiehuntong.beans.ErrorBean;
import a66weding.com.jiehuntong.beans.HttpRequestBean;
import a66weding.com.jiehuntong.beans.MarriageProposalBean;
import a66weding.com.jiehuntong.beans.MarriageProposalHeadBean;
import a66weding.com.jiehuntong.beans.SuccessBean;
import a66weding.com.jiehuntong.common.MessageEvent;
import a66weding.com.jiehuntong.common.utils.CUtils;
import a66weding.com.jiehuntong.common.utils.DateUtils;
import a66weding.com.jiehuntong.common.utils.ImageOptionsUtil;
import a66weding.com.jiehuntong.common.utils.LogUtil;
import a66weding.com.jiehuntong.common.utils.Utils;
import a66weding.com.jiehuntong.http.HttpHandleUtil;
import a66weding.com.jiehuntong.http.OnNetResultListener;
import a66weding.com.jiehuntong.http.RequestCode;
import a66weding.com.jiehuntong.http.UrlDealUtil;
import a66weding.com.jiehuntong.inner.ScrollListener;
import a66weding.com.jiehuntong.view.ConfirmLoginDialog;
import a66weding.com.jiehuntong.widgets.CircularImage;
import a66weding.com.jiehuntong.widgets.RoundProgressBar;
import a66weding.com.jiehuntong.widgets.ScrollForeverTextView;
import a66weding.com.jiehuntong.widgets.View_group;
import a66weding.com.jiehuntong.widgets.scoll.Diy_Scroll;
import a66weding.com.jiehuntong.widgets.scoll.RevailView;

/**
 * 结婚
 * Created by y on 2016/5/17.
 */
public class DiyPager extends BasePager implements View.OnClickListener, OnNetResultListener, ScrollListener {

    private View myDiyView;// 父view
    private RelativeLayout pig_title;// 标题布局
    private RelativeLayout mainRl;// 头部布局
    private RelativeLayout diy_rl;// 剩余金额布局
    private RelativeLayout diy_r2;// 剩余天数布局
    private RoundProgressBar mRoundProgressBar1;// 剩余金额圆形进度控件
    private RoundProgressBar mRoundProgressBar2;// 剩余天数圆形进度控件
    private ScrollForeverTextView diy_money_tv;// 剩余金额控件
    private ScrollForeverTextView shengyutime_tv;// 剩余天数
    private TextView piygager_total_bug;// 预算金额控件
    private TextView diypager_day;// 结婚婚期控件
    private RevailView revailView;// 头部缩放控件
    private RelativeLayout main_view;// 头部背景控件
    private RelativeLayout headPortrait_group;// 头像布局
    private CircularImage headPortrait;// 头像控件
    private Diy_Scroll diy_scroll;// 跑道卷轴
    private View_group viewGroup;// 跑道控件
    private ImageView task_icon_iamge1;// 计划背景
    private CircularImage item_bg_icon;// 计划图片
    private CircularImage item_bg_icon_comple;// 计划完成
    private TextView item_name;// 计划类型
    private TextView mission_personnel_name1;// 计划协助人
    private ImageView myTask;// 任务控件
    private ImageView myHelper;// 帮手控件
    private RelativeLayout heightScrollRl;// 卷轴内部控件
    private SwipeRefreshLayout xRefreshView;// 刷新控件
    private RelativeLayout topRl;// 刷新控件父布局
    private MarriageProposalBean marriageProposalBean;// 计划书实体（跑道数据）
    private List<MarriageProposalBean.DataBean> dataBeenList;// 计划书实体（跑道集合数据）
    private MarriageProposalHeadBean marriageProposalHeadBean;// 计划书信息实体（头部数据）
    private int[] positionX = new int[]
            {145, 75, 184, 155, 104, 59, 123,
                    105, 120, 153, 147, 138, 63, 152, 126};
    private int[] positionY = new int[]
            {15, 50, 125, 194, 245, 304, 400,
                    514, 633, 732, 833, 968, 1018, 1137, 1284};
    private static final int ANIMATION_DURATION = 200;
    private final Interpolator INTERPOLATOR = new FastOutSlowInInterpolator();
    private static final int HEAD_DURATION = 200;
    private static final int BASE_PAGER_REQUEST_LOGIN_CODE =3000;

    /*
    跑道内计划：  300ms
    各计划时间差：200ms
    头部红条缩放：200ms
    头像移动：    200ms
    */

    private int screenWidth;// 屏幕宽度
    private int screenHeight;// 屏幕高度
    public DiyPager(Activity activity) {
        super(activity);
    }

    @TargetApi(Build.VERSION_CODES.M)
    @Override
    protected View getView() {
        myDiyView = View.inflate(mActivity, R.layout.activity_diy_home, null);
        pig_title = (RelativeLayout) myDiyView.findViewById(R.id.pig_title);
        mainRl = (RelativeLayout) myDiyView.findViewById(R.id.main);
        diy_rl = (RelativeLayout) myDiyView.findViewById(R.id.diy_rfdng);
        diy_r2 = (RelativeLayout) myDiyView.findViewById(R.id.diy_slngg);
        mRoundProgressBar1 = (RoundProgressBar) myDiyView.findViewById(R.id.roundProgressBar1);
        mRoundProgressBar2 = (RoundProgressBar) myDiyView.findViewById(R.id.roundProgressBar2);
        piygager_total_bug = (TextView) myDiyView.findViewById(R.id.piygager_total_bug);
        diypager_day = (TextView) myDiyView.findViewById(R.id.diypager_day);
        revailView = (RevailView) myDiyView.findViewById(R.id.revailview);
        revailView.setColor(mActivity.getResources().getColor(R.color.colorMainRed));
        main_view = (RelativeLayout) myDiyView.findViewById(R.id.main_view);
        headPortrait = (CircularImage) myDiyView.findViewById(R.id.headPortrait);
        viewGroup = (View_group) myDiyView.findViewById(R.id.vg_re);
        diy_money_tv = (ScrollForeverTextView) myDiyView.findViewById(R.id.diy_money_tv);
        headPortrait_group = (RelativeLayout) myDiyView.findViewById(R.id.headPortrait_group);
        diy_scroll = (Diy_Scroll) myDiyView.findViewById(R.id.piy_scroll);
        shengyutime_tv = (ScrollForeverTextView) myDiyView.findViewById(R.id.shengyutime_tv);
        heightScrollRl = (RelativeLayout) myDiyView.findViewById(R.id.height_scroll_rl);
        topRl = (RelativeLayout) myDiyView.findViewById(R.id.top_rl);
        xRefreshView = (SwipeRefreshLayout) myDiyView.findViewById(R.id.help_refresh);
        xRefreshView.setColorSchemeResources(R.color.colorMainRed);
        xRefreshView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if (isLogin()) {
                    initData();
                } else {
                    xRefreshView.setRefreshing(false);
                }
            }
        });

        myTask = (ImageView) myDiyView.findViewById(R.id.myTask);
        myHelper = (ImageView) myDiyView.findViewById(R.id.myHelper);

        mRoundProgressBar1.setCricleProgressColor(mActivity.getResources().getColor(R.color.colorProgress));
        mRoundProgressBar2.setCricleProgressColor(Color.parseColor("#f2e30d"));

        headPortrait.setOnClickListener(this);
        myTask.setOnClickListener(this);
        myHelper.setOnClickListener(this);
        diy_scroll.setScrolllistener(this);
        diy_scroll.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(event.getAction() == MotionEvent.ACTION_DOWN){
                    isUnscroll = true;
                }
                if(!isUnscroll){// 设置不可滑动
                    return true;
                }
                return false;
            }
        });

        screenWidth = Utils.getScreenWidth(mActivity);
        screenHeight = Utils.getScreenHeight(mActivity);
        return myDiyView;
    }

    private Handler mhandler = new Handler() {
        @Override
        public void handleMessage(final Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 1:// 剩余天数
                    final int surplusDays = msg.arg1;
                    final int countDays = msg.arg2;
                    if(surplusDays > 0){
                        shengyutime_tv.setText(surplusDays + "天");
                    } else if(surplusDays == 0){
                        shengyutime_tv.setText("结婚日");
                    } else {
                        shengyutime_tv.setText("喜结连理");
                    }

                    if(surplusDays > 0 && countDays > 0){
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                for (int i=0; i <= count - 1; i++){
                                    Message message = mhandler.obtainMessage();
                                    message.what = 4;
                                    message.arg1 = (int) (surplusDays * 1.0 / count * (i + 1));
                                    message.arg2 = countDays;
                                    mhandler.sendMessage(message);
                                    try {
                                        Thread.sleep(ANIMATION_DURATION / count * 2);
                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }).start();
                    }
                    break;
                case 2:// 剩余金额
                    final int surplusMoney = msg.arg1;
                    final int countMoney = msg.arg2;
                    if (surplusMoney > 0) {
                        diy_money_tv.setText("" + surplusMoney);
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                for (int i=0; i <= count - 1; i++){
                                    Message message = mhandler.obtainMessage();
                                    message.what = 3;
                                    message.arg1 = (int) (surplusMoney * 1.0 / count * (i + 1));
                                    message.arg2 = countMoney;
                                    mhandler.sendMessage(message);
                                    try {
                                        Thread.sleep(ANIMATION_DURATION / count * 2);
                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }).start();
                    } else {
                        diy_money_tv.setText(" 0");
                    }
                    break;
                case 3:
                    mRoundProgressBar1.setProgress(msg.arg1);
                    mRoundProgressBar1.setMax(msg.arg2);
                    mRoundProgressBar1.invalidate();
                    break;
                case 4:
                    mRoundProgressBar2.setProgress(msg.arg1);
                    mRoundProgressBar2.setMax(msg.arg2);
                    mRoundProgressBar2.invalidate();
                    break;
                case 5:// 卷轴位置动态移动
                    int paddingTop = msg.arg1;
                    topRl.setPadding(0,paddingTop,0,0);
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * 动画总和;
     */
    //隐藏动画;
    private void hide() {
        startHideAnimation();
        Animator contractAnimator = revailView.contract();
        setupAnimationParams(contractAnimator);
        AnimatorSet set = new AnimatorSet();
        set.play(contractAnimator);
        set.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                //
                mainRl.setVisibility(View.INVISIBLE);
                if (!isVisable) {
                    viewanim();
                    diy_scroll.requestLayout();
                }
            }

            @Override
            public void onAnimationStart(Animator animation) {
                super.onAnimationStart(animation);
                main_view.setAlpha(0);
            }

            @Override
            public void onAnimationResume(Animator animation) {
                super.onAnimationResume(animation);
            }
        });
        set.start();
    }

    //显示动画;
    private void display() {
        statXsh();
        Animator contractAnimator = revailView.expand();
        setupAnimationParams(contractAnimator);
        AnimatorSet set = new AnimatorSet();
        set.play(contractAnimator);
        set.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                mainRl.setVisibility(View.VISIBLE);
                if (isVisable) {
                    viewanim2();
                    main_view.setAlpha(1);
                }
            }

            @Override
            public void onAnimationStart(Animator animation) {
                super.onAnimationStart(animation);
                mainRl.setVisibility(View.VISIBLE);
            }

            @Override
            public void onAnimationResume(Animator animation) {
                super.onAnimationResume(animation);
                mainRl.setVisibility(View.VISIBLE);
            }
        });
        set.start();
    }

    private void startHideAnimation() {
        diy_rl.setVisibility(View.INVISIBLE);
        diy_r2.setVisibility(View.INVISIBLE);
        ObjectAnimator alphaAnimator = ObjectAnimator.ofFloat(diy_rl, "alpha", 1, 0);
        ObjectAnimator alphaAnimator1 = ObjectAnimator.ofFloat(diy_r2, "alpha", 1, 0);
        alphaAnimator.start();
        alphaAnimator1.start();
        //隐藏
    }

    //移动位置;
    public void viewanim() {
        PropertyValuesHolder pvhX = PropertyValuesHolder.ofFloat("alpha", 1f, 0.1f, 1f);
        PropertyValuesHolder pvhY = PropertyValuesHolder.ofFloat("y", DensityUtil.dip2px(59), DensityUtil.dip2px(-9));
        PropertyValuesHolder pvhX1 = PropertyValuesHolder.ofFloat("x", screenWidth / 2 - headPortrait_group.getMeasuredWidth() / 2, DensityUtil.dip2px(-9));
        ObjectAnimator.ofPropertyValuesHolder(headPortrait_group, pvhX, pvhY, pvhX1).setDuration(HEAD_DURATION).start();
        isVisable = true;
        scaltoSmall();
    }

    public void viewanim2() {
        PropertyValuesHolder pvhX = PropertyValuesHolder.ofFloat("alpha", 1f, 0.1f, 1f);
        PropertyValuesHolder pvhY = PropertyValuesHolder.ofFloat("y", DensityUtil.dip2px(-9), DensityUtil.dip2px(59));
        PropertyValuesHolder pvhX1 = PropertyValuesHolder.ofFloat("x", DensityUtil.dip2px(-9), screenWidth / 2 - headPortrait_group.getMeasuredWidth() / 2);
        ObjectAnimator.ofPropertyValuesHolder(headPortrait_group, pvhX, pvhY, pvhX1).setDuration(HEAD_DURATION).start();

        isVisable = false;
        scaltolarge();
    }

    private View item;

    @Override
    public void initData() {
        //加在头像;
        if (isLogin()) {
            getProcessData();
            String headUrl = DataWareHourse.getInstance().getmUser().getData().get(0).getNvc_TitlePhoto();
            if (!TextUtils.isEmpty(headUrl)) {
                LogUtil.i("headUrl", headUrl);
                x.image().bind(headPortrait, headUrl);
            }
        } else {
            measureLv(viewGroup);
        }
    }

    @Override
    public void notifyData() {
        if (isLogin()) {
            String headUrl = DataWareHourse.getInstance().getmUser().getData().get(0).getNvc_TitlePhoto();
            if (!TextUtils.isEmpty(headUrl)) {
                LogUtil.i("headUrl", headUrl);
                x.image().bind(headPortrait, headUrl);
            }
        }
    }

    @Subscribe
    public void onEvent(MessageEvent event) {
    }

    /**
     * 得到流程数据
     */
    private void getProcessData() {
        String userUrl = UrlDealUtil.getRealUrl(RequestCode.SELECT_PLANBOOK);
        HttpRequestBean requestBean1 = new HttpRequestBean(RequestCode.POSTEQUEST, userUrl, this, MarriageProposalHeadBean.class, RequestCode.SELECT_PLANBOOK);
        HttpHandleUtil.executeCommonPost(mActivity, requestBean1);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //点击头像
            case R.id.headPortrait:
                if (isLogin()) {
                    Intent headIamge = new Intent(mActivity, Diy_HeadActivity.class);
                    if (dataBeenList != null) {
                        headIamge.putExtra("flag", (Serializable) dataBeenList);
                    }
                    mActivity.startActivityForResult(headIamge, MainActivity.getResultCode);
                } else {
                    showLoginDialog(BASE_PAGER_REQUEST_LOGIN_CODE+1);
                }
                break;
            case R.id.myTask:// 任务
                if (isLogin()) {
                    Intent intent_task = new Intent(mActivity, MyTaskActivity.class);
                    mActivity.startActivity(intent_task);
                } else {
                    showLoginDialog(BASE_PAGER_REQUEST_LOGIN_CODE+2);
                }
                break;
            case R.id.myHelper://帮手
                if (isLogin()) {
                    Intent intent_helper = new Intent(mActivity, FindHelp.class);
                    mActivity.startActivity(intent_helper);
                } else {
                    showLoginDialog(BASE_PAGER_REQUEST_LOGIN_CODE+3);
                }
                break;

        }
    }

    @Override
    public void onSucess(SuccessBean sucessbean) {
        Object data = sucessbean.getData();
        if (data instanceof MarriageProposalBean) {
            marriageProposalBean = (MarriageProposalBean) data;
            String totalPrice;// 总预算
            double totalMoney;// 各计划预计钱数总共
            xRefreshView.setRefreshing(false);
            switch (marriageProposalBean.getResCode()) {
                case "0000":
                    //设置适配器
                    viewGroup.removeAllViews();
                    if (marriageProposalBean.getData() != null) {
                        dataBeenList = quChong(marriageProposalBean.getData());
                    } else {
                        break;
                    }
                    totalMoney = getlumpSum(dataBeenList);
                    totalPrice = marriageProposalHeadBean.getData().get(0).getNvc_WeddingBudget();
                    if (!TextUtils.isEmpty(totalPrice)) {
                        Message message = mhandler.obtainMessage();
                        message.what = 2;
                        message.arg1 = (int) ((Double.parseDouble(totalPrice) - totalMoney));
                        message.arg2 = (int) Double.parseDouble(totalPrice);
                        mhandler.sendMessage(message);
                    }

                    int index = 0;
                    for (int i = 0; i < dataBeenList.size(); i++) {
                        item = View.inflate(mActivity, R.layout.item, null);
                        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
                        lp.leftMargin = (int) (positionX[i] * 1.0 / 360 * screenWidth);
                        lp.topMargin = DensityUtil.dip2px(positionY[i]);
                        if (dataBeenList.get(i) == null) {
                            continue;
                        }
                        item_name = (TextView) item.findViewById(R.id.task_name);
                        task_icon_iamge1 = (ImageView) item.findViewById(R.id.task_icon_iamge1);
                        mission_personnel_name1 = (TextView) item.findViewById(R.id.mission_personnel_name1);
                        item_bg_icon = (CircularImage) item.findViewById(R.id.item_bg_icon);
                        item_bg_icon_comple = (CircularImage) item.findViewById(R.id.item_bg_icon_comple);

                        item_name.setText(dataBeenList.get(i).getBookTitle());

                        int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
                        int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
                        item_name.measure(w, h);
                        int width = item_name.getMeasuredWidth();
                        int widthParent = Utils.dip2px(mActivity, 45);

                        //如果是完成状态
                        //判断是否修改过;
                        if (isChange(dataBeenList.get(i))) {
                            task_icon_iamge1.setImageDrawable(mActivity.getResources().getDrawable(R.mipmap.task_icon));
                        } else {
                            task_icon_iamge1.setImageDrawable(mActivity.getResources().getDrawable(R.mipmap.no_edited));
                        }

                        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                        if (width > widthParent) {
                            mission_personnel_name1.setPadding(width - Utils.dip2px(mActivity, 1), 0, 0, 0);
                        } else {
                            mission_personnel_name1.setPadding((width + widthParent) / 2 - Utils.dip2px(mActivity, 1), 0, 0, 0);
                        }
                        //真实姓名
                        String realname = dataBeenList.get(i).getNvc_RealName();
                        //模拟姓名
                        String nvcname = dataBeenList.get(i).getNvc_Name();
                        if (!TextUtils.isEmpty(realname)) {
                            mission_personnel_name1.setText("（" + realname + "）");
                        } else if (!TextUtils.isEmpty(nvcname)) {
                            mission_personnel_name1.setText("（" + nvcname + "）");
                        }
                        if (dataBeenList.get(i).getPicture() != null) {
                            x.image().bind(item_bg_icon, dataBeenList.get(i).getPicture(), ImageOptionsUtil.getcircle_fixy());
                        }
                        if (dataBeenList.get(i).isIsComplete()) {
                            item_bg_icon_comple.setVisibility(View.VISIBLE);
                            item_bg_icon_comple.setImageResource(R.mipmap.heisebg);
                            item_bg_icon_comple.setAlpha(0.4f);
                        }

                        index = i;
                        final int finalIndex = index;
                        item.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Intent intent = new Intent(mActivity, JobDetailActivity.class);
                                MarriageProposalBean.DataBean databeen = dataBeenList.get(finalIndex);
                                intent.putExtra("headpictrue", databeen.getPicture());
                                intent.putExtra(JobDetail.TASK_FLAG, databeen);
                                intent.putExtra("flag", 7);
                                mActivity.startActivityForResult(intent, 10);
                            }
                        });
                        item.setOnTouchListener(new View.OnTouchListener() {
                            @Override
                            public boolean onTouch(View v, MotionEvent event) {
                                if(event.getAction() == MotionEvent.ACTION_DOWN){
                                    isUnscroll = true;
                                }
                                return false;
                            }
                        });
                        viewGroup.addView(item, lp);
                    }

                    Animation animation = AnimationUtils.loadAnimation(mActivity, R.anim.tween_enter);
                    LayoutAnimationController lac = new LayoutAnimationController(animation);
                    lac.setOrder(LayoutAnimationController.ORDER_NORMAL);
                    lac.setDelay((float) 0.2);
                    viewGroup.setLayoutAnimation(lac);
                    measureLv(viewGroup);

                    break;
                case "0003":// 无计划数据
                    viewGroup.removeAllViews();
                    if (dataBeenList != null) {
                        dataBeenList.clear();
                    }
                    totalMoney = 0;
                    totalPrice = marriageProposalHeadBean.getData().get(0).getNvc_WeddingBudget();
                    if (!TextUtils.isEmpty(totalPrice)) {
                        Message message = mhandler.obtainMessage();
                        message.what = 2;
                        message.arg1 = ((int) (Double.parseDouble(totalPrice)) - (int) totalMoney);
                        message.arg2 = (int) Double.parseDouble(totalPrice);
                        mhandler.sendMessage(message);
                    }
                    measureLv(viewGroup);
                    break;
            }
        }

        if (data instanceof MarriageProposalHeadBean) {
            marriageProposalHeadBean = (MarriageProposalHeadBean) data;
            switch (marriageProposalHeadBean.getResCode()) {
                case "0000":
                    List<MarriageProposalHeadBean.DataBean> headDataBeans = marriageProposalHeadBean.getData();
                    if (headDataBeans != null && headDataBeans.size() > 0 && headDataBeans.get(0) != null) {
                        MarriageProposalHeadBean.DataBean headDataBean = headDataBeans.get(0);
                        String totalPrice = headDataBean.getNvc_WeddingBudget();
                        if (!TextUtils.isEmpty(totalPrice)) {
                            if (totalPrice.contains(".00")) {
                                totalPrice.replace(".00", "");
                            }
                            if (totalPrice.contains(".0")) {
                                totalPrice = totalPrice.replace(".0", "");
                            }
                            piygager_total_bug.setText(totalPrice);
                        }
                        if (!TextUtils.isEmpty(headDataBean.getNvc_WeddingDate())) {
                            diypager_day.setText(headDataBean.getNvc_WeddingDate());
                            Message message = mhandler.obtainMessage();
                            message.what = 1;
                            // 剩余天数：从当天到婚期，可为负数
                            message.arg1 = DateUtils.daysBetween(refFormatNowDate(), headDataBean.getNvc_WeddingDate());
                            String updateDate = headDataBean.getDt_UpdateDate().toString();
                            if(updateDate.contains("T")){
                                updateDate = updateDate.split("T")[0];
                                // 总天数：从设定日期到婚期，
                                message.arg2 = DateUtils.daysBetween(updateDate, headDataBean.getNvc_WeddingDate());
                            }
                            mhandler.sendMessage(message);
                        }

                        String userUrl1 = UrlDealUtil.getRealUrl(RequestCode.RETURN_PROCESS);
                        HttpRequestBean requestBean = new HttpRequestBean(RequestCode.POSTEQUEST, userUrl1, this, MarriageProposalBean.class, RequestCode.RETURN_PROCESS);
                        HttpHandleUtil.executeCommonPost(mActivity, requestBean);
                    }
                    break;
                default:
                    xRefreshView.setRefreshing(false);
                    CUtils.showToast(marriageProposalHeadBean.getMsg());
                    break;
            }
        }
    }

    private List<MarriageProposalBean.DataBean> quChong(List<MarriageProposalBean.DataBean> datas) {
        List<MarriageProposalBean.DataBean> newDatas = new ArrayList<MarriageProposalBean.DataBean>();
        for (MarriageProposalBean.DataBean data : datas) {
            boolean noHas = true;
            for (MarriageProposalBean.DataBean newData : newDatas) {
                if (data.getBookTitle().equals(newData.getBookTitle())) {
                    noHas = false;
                    break;
                }
            }
            if (noHas && newDatas.size() < 15) {
                newDatas.add(data);
            }
        }
        return newDatas;
    }


    //判断流程是否修改过
    private boolean isChange(MarriageProposalBean.DataBean dataBean) {
        boolean flag;
        if (dataBean.getBudgetMoney() == 0 &&
                TextUtils.isEmpty(dataBean.getBookPlace()) &&
                TextUtils.isEmpty(dataBean.getAssignDate()) &&
                TextUtils.isEmpty(dataBean.getNvc_Name()) &&
                TextUtils.isEmpty(dataBean.getPicture()) &&
                TextUtils.isEmpty(dataBean.getRelationName()) &&
                TextUtils.isEmpty(dataBean.getNvc_RealName())) {
            flag = false;
        } else {
            flag = true;
        }
        return flag;
    }

    /**
     * 获取各个任务所用的金额;
     */
    private double getlumpSum(List<MarriageProposalBean.DataBean> dataBeenList) {
        int totaltotal = 0;
        for (int i = 0; i < dataBeenList.size(); i++) {
            totaltotal += dataBeenList.get(i).getBudgetMoney();
        }
        return totaltotal;
    }

    @Override
    public void onError(ErrorBean errorBean) {
        xRefreshView.setRefreshing(false);
        CUtils.showToast("请求数据错误，请稍后再试！");
    }

    private boolean iskejian = false;

    boolean isUnscroll = true;// 滑动是否可用
    int count = 20;

    @Override
    public void change(int y) {

        if (y <= 0) {
            if (iskejian) {
                isUnscroll = false;
                display();
                iskejian = false;
//                topRl.setPadding(0,DensityUtil.dip2px(105),0,0);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        for (int i=0; i <= count - 1; i++){
                            Message message = mhandler.obtainMessage();
                            message.what = 5;
                            message.arg1 = (int) (DensityUtil.dip2px(105) * 1.0 / count * (i + 1));
                            mhandler.sendMessage(message);
                            try {
                                Thread.sleep(ANIMATION_DURATION / count);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }).start();

            }
        } else if (y >= DensityUtil.dip2px(0)) {
            if (!iskejian) {
                isUnscroll = false;
                hide();
                iskejian = true;
//                topRl.setPadding(0,0,0,0);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        for (int i=0; i <= count - 1; i++){
                            Message message = mhandler.obtainMessage();
                            message.what = 5;
                            message.arg1 = (int) (DensityUtil.dip2px(105) * 1.0 / count * (count - 1 - i));
                            mhandler.sendMessage(message);
                            try {
                                Thread.sleep(ANIMATION_DURATION / count);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }).start();
            }
        }
    }

    private boolean isLogin;

    private boolean isLogin() {
        isLogin = ((GlobalApplication) mActivity.getApplication()).isLogin();
        return isLogin;
    }

    public void showLoginDialog(final int requestlogincode) {
        final ConfirmLoginDialog confirmDialog = new ConfirmLoginDialog(mActivity, "亲，需要登录哦~", "去登录", "取消", R.layout.pop_tologin);
        confirmDialog.show();
        confirmDialog.setClicklistener(new ConfirmLoginDialog.ClickListenerInterface() {
            @Override
            public void doConfirm() {
                Intent intent = new Intent(mActivity, LoginActivity.class);
                mActivity.startActivityForResult(intent,requestlogincode);
                confirmDialog.dismiss();
            }
            @Override
            public void doCancel() {
                confirmDialog.dismiss();
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==(BASE_PAGER_REQUEST_LOGIN_CODE+1)&&resultCode==LoginActivity.RESULT_OK){//头像
            Intent headIamge = new Intent(mActivity, Diy_HeadActivity.class);
            if (dataBeenList != null) {
                headIamge.putExtra("flag", (Serializable) dataBeenList);
            }
            mActivity.startActivityForResult(headIamge, MainActivity.getResultCode);

        }   else if (requestCode==(BASE_PAGER_REQUEST_LOGIN_CODE+2)&&resultCode==LoginActivity.RESULT_OK){//任务
            Intent intent_task = new Intent(mActivity, MyTaskActivity.class);
            mActivity.startActivity(intent_task);
        }   else   if (requestCode==(BASE_PAGER_REQUEST_LOGIN_CODE+3)&&resultCode==LoginActivity.RESULT_OK){//我的任务
            Intent intent_helper = new Intent(mActivity, FindHelp.class);
            mActivity.startActivity(intent_helper);
        }
    }

    //是否显示;
    private boolean isVisable;//为true 不显示状态 ;
    //头像的位移;
    //显示动画;
    private void statXsh() {
        diy_rl.setVisibility(View.VISIBLE);
        diy_r2.setVisibility(View.VISIBLE);
        ObjectAnimator alphaAnimator = ObjectAnimator.ofFloat(diy_rl, "alpha", 0, 1);
        ObjectAnimator alphaAnimator1 = ObjectAnimator.ofFloat(diy_r2, "alpha", 0, 1);
        alphaAnimator.start();
        alphaAnimator1.start();
    }

    //给动画设置参数;
    private void setupAnimationParams(Animator animator) {
        animator.setInterpolator(INTERPOLATOR);
        animator.setDuration(ANIMATION_DURATION);
    }

    public void measureLv(ViewGroup view) {
        int height = 0;
        int count = view.getChildCount();
        if (count > 0 && count < positionY.length) {
            height = DensityUtil.dip2px(positionY[count - 1] + 120);
        } else if(count == positionY.length){
            height = DensityUtil.dip2px(1450);
        }
        if (height < screenHeight - DensityUtil.dip2px(105)) {
            height = screenHeight - DensityUtil.dip2px(105);
        }
        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) heightScrollRl.getLayoutParams();
        lp.height = height;
        heightScrollRl.setLayoutParams(lp);
        diy_scroll.requestLayout();
    }

    //头像变小;
    private void scaltoSmall() {
        ObjectAnimator anim1 = ObjectAnimator.ofFloat(headPortrait_group, "scaleX",
                1.0f, 0.5f);
        ObjectAnimator anim2 = ObjectAnimator.ofFloat(headPortrait_group, "scaleY",
                1.0f, 0.5f);
        AnimatorSet animSet = new AnimatorSet();
        animSet.play(anim1).with(anim2);
        animSet.setDuration(HEAD_DURATION);
        animSet.start();
    }

    //头像变大
    private void scaltolarge() {
        ObjectAnimator anim1 = ObjectAnimator.ofFloat(headPortrait_group, "scaleX",
                0.5f, 1f);
        ObjectAnimator anim2 = ObjectAnimator.ofFloat(headPortrait_group, "scaleY",
                0.5f, 1f);
        AnimatorSet animSet = new AnimatorSet();
        animSet.play(anim1).with(anim2);
        animSet.setDuration(HEAD_DURATION);
        animSet.start();
    }

    /**
     * 获取时间 yyyy-MM-dd
     * 根据当前毫秒值转化为字符串;
     */
    public String refFormatNowDate() {
        Date nowTime = new Date(System.currentTimeMillis());
        SimpleDateFormat sdFormatter = new SimpleDateFormat("yyyy-MM-dd");
        String retStrFormatNowDate = sdFormatter.format(nowTime);
        return retStrFormatNowDate;
    }
}
